package org.example.sync;

import java.util.Date;

/**
 * @author zhaoPin
 * @Date 2024/9/9  17:43
 * @description: 通过 对比 {@link SynchronizedOldDemo} 采用代码块优化的方式可以更快的执行结果
 * 这里的底层就蕴含着 Synchronized 在针对代码块的 锁升级的过程
 */
public class SynchronizedDemo implements Runnable {
    private static int count = 0;

    public static void main(String[] args) {
        final var start = new Date();

        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(new SynchronizedDemo());
            thread.start();
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        final var end =new Date();
        final var l = end.getTime() - start.getTime();
        System.out.println("result: " + count + " time:" + l);
    }

    @Override
    public void run() {
        // 通过代码块方式执行就非常快
        synchronized (SynchronizedDemo.class) {
            for (int i = 0; i < 1000000; i++){
                count++;
            }
        }
    }


}